<template > 
<a-card >
  <a-card :bordered="false" size="small" title="流程操作">
    <template #extra>流程已启动：{{ startTime }} 
    </template>
  </a-card>  
  
  <a-card :bordered="false" >
    <a-radio-group v-model:value="operation" name="rdOperation">            
      <a-radio value="discard">修改当前处理人</a-radio>
      <a-radio value="approve">前后跳转</a-radio>      
      <a-radio value="communicate">终审通过</a-radio>      
      <a-radio value="signature">直接废弃</a-radio>                  
      <a-radio value="reject">流程暂停</a-radio>
      <a-radio value="transfer">节点暂停</a-radio>
    </a-radio-group>   
    <a-card :bordered="false" size="small" title="修改当前处理人" v-if="operation == 'circulate'">
      <a-form-item label="处理人：" name="circulateleader" label-align="left">
        <div style="
            border: 1px solid #e6e8eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
          ">
          <a-space>
            <div style="overflow: auto" class="tagboxs">
              <a-tag closable @close="handleCloseCommunicate(toolbarSettings.circulatePersons)"
                v-for="tag in toolbarSettings.circulatePersons" :key="tag">
                {{ tag }}
              </a-tag>
            </div>
          </a-space>
          <a-tooltip title="请选择处理人">
            <n-button style="margin-left: auto" size="small" secondary type="info"
              @click="openUserModal(null, 'circulate')">
              <template #icon>
                <UserOutlined />
              </template>
            </n-button>
          </a-tooltip>
        </div>
      </a-form-item>
    </a-card>

  </a-card>
  <a-card :bordered="false" size="small" title="处理意见">
    <a-textarea v-model:value="userRquest.comments" placeholder="请输入处理意见" :auto-size="{ minRows: 2, maxRows: 5 }" />
    <br /><br />
    <a-upload v-model:file-list="fileList" 
      :before-remove="removeFile" 
      :action="api.uploadfiles" >
      <a-button>
        <upload-outlined></upload-outlined>
        上传附件
      </a-button>
      <template #itemRender="{ file, actions }">
        <a-space>
          <span>{{ file.name }}</span>
          <a href="javascript:;" @click="actions.download">预览</a>
          <a href="javascript:;" @click="actions.download">下载</a>
          <a href="javascript:;" @click="handleRemove(file)">删除</a>
        </a-space>
      </template>
    </a-upload>
    <br />
    <a-button type="primary" @click="appoveOperation">提交</a-button>    
  </a-card>
  <a-card :bordered="false" size="small">
    <a-collapse v-model:activeKey="activeKey1" :bordered="false" style="background: rgb(255, 255, 255)">
      <template #expandIcon="{ isActive }">
        <caret-down-outlined :rotate="isActive ? 180 : 0" />
      </template>
      <a-collapse-panel key="1" header="流程走向" :style="customStyle">
        <p>当前节点：</p>
        <p>{{ toolbarSettings.willgoNode.currentNodeInfo }}</p>
        <p>下一节点：</p>
        <p>{{ toolbarSettings.willgoNode.nextNodeInfo }}</p>
      </a-collapse-panel>
    </a-collapse>
  </a-card>      
</a-card>
</template>

<script lang="tsx" setup>
import { ref, nextTick, reactive, unref, onMounted, watch, defineComponent } from 'vue';
import { monitorToolbar } from './monitorToolbar';
import { isEmpty, isNullOrUnDef } from '@/utils/is/';
import constants from '@/utils/constants';
import { UploadOutlined } from '@ant-design/icons-vue';
import { message,type UploadChangeParam,type UploadProps,type UploadFile } from 'ant-design-vue';
import { CaretDownOutlined, UserOutlined } from '@ant-design/icons-vue';
import { getToolbarSettings } from '@/api/flow/review';

import type { SelectProps } from 'ant-design-vue';
import { useModal } from '@/hooks/useModal/useModal';
import type { FormInstance } from 'ant-design-vue';
import userMore from '@/components/system/orgUserMore/userMore.vue';
import userSingle from '@/components/system/orgUserSingle/userSingle.vue';
import SettingOrg from '@/components/setting/assigneeSetting.vue';
import api from '@/core/permission/modules/form/index';
import { useUserStore } from '@/store/modules/user';
import {deleteFile} from '@/api/form/index';
import { Modal } from 'ant-design-vue';
// import { fa } from 'element-plus/es/locale';
import {saveFormDataValue} from '@/api/form/index';

defineComponent({
  userSingle,
  userMore
}
)
const confirmVisible = ref(false);
const editFormRef = ref<any>(null);

const onSubMit = () => {
  return [null, null]
};
const handleClose = (item) => {
  item.nodeValues = [];
  item.selectedNodeValues = "";
}
//附件删除事件
const handleRemove = async(file: any) => { 
  const index = fileList.value.findIndex(item => item.uid === file.uid);
  if (index !== -1) {
    fileList.value.splice(index, 1);
    const res=await deleteFile({filePath:file.response.result.filePath})
  }
};

const userStore = useUserStore();
const editDrawerBindValue = reactive({
  defaultSelectData: [],
  selectedKey: '',
   runType:''
});


const inclusiveGatewayList = ref([]);


const [ModalRender, modalRef] = useModal();
const userSingleRef = ref<FormInstance>();
const openModal = async () => {
  ModalRender.show({
    title: '选择处理人员',
    width: '70%',
    // 是否显示右上角确定取消
    defaultExtra: true,
    destroyOnClose: true,
    content: () => {
      return <userSingle ref={userSingleRef} defaultData={unref(editDrawerBindValue)}></userSingle>;
    },
    // 确定方法执行
    onOk: async (values) => {
      const res = await userSingleRef.value?.handleSubmit();
      if (!res) return;
      toolbarSettings.transferToUserName.push(res.NAME);
      transferToUserId.value = res.NO;      
    },
  });
};
const openUserModal = async (item, operation) => {
  if (item == null)
    editDrawerBindValue.selectedKey = operation;
  else
    editDrawerBindValue.selectedKey = item.nodeKey;
  ModalRender.show({
    title: '选择处理人员',
    width: '70%',
    // 是否显示右上角确定取消
    defaultExtra: true,
    destroyOnClose: true,
    content: () => {
      return <userMore ref={userSingleRef} defaultData={unref(editDrawerBindValue)} > </userMore>;
    },
    // 确定方法执行
    onOk: async (values) => {
      const res = await userSingleRef.value?.handleSubmit();
      if (!res) return;
      if (res.length > 0) {
        updateSelected(res);
      }
    },
  });
};

const openUserSelectedModal = async(activity)=>{
    editDrawerBindValue.runType='0';
    editDrawerBindValue.defaultSelectData=activity.nodeValues;
    currentSelectedActivitiyId.value = activity.nodeKey;
    ModalRender.show({
      title: '选择处理人',
      width: '70%',
      // 是否显示右上角确定取消
      defaultExtra: true,
      destroyOnClose: true,
      content: () => {
        return <SettingOrg  ref={editFormRef} defaultData={unref(editDrawerBindValue)}></SettingOrg>;
      },
      // 确定方法执行
      onOk: async (values) => {        
        const res = await editFormRef.value?.handleSubmit();               
        if (!res) return;
        let newNodeValue:activityApproveUser;
        newNodeValue = {
          activityId:currentSelectedActivitiyId.value,
          users:res
        } 
        setSelectedModfiyNodes(newNodeValue);        
        console.log(res);        
      },
    });
  };

function setSelectedModfiyNodes(node){
  let update = false;
  modifyNodes.value.forEach(item=>{
    if(item.activityId===node.activityId){
      item.users =node.users;    
      update = true;              
    }
  });
  if(!update){
    modifyNodes.value.push(node);
  } 
  let nodeValues = "";
  node.users.forEach(item=>{
      nodeValues += item.NAME + ",";
  });
  nodeValues = nodeValues.substring(0,nodeValues.length -1);
  toolbarSettings.modifyNodes.forEach(item=>{
      if(item.nodeKey===node.activityId){
        item.nodeValues = nodeValues.split(",");
      }
  });
  console.log(nodeValues);

}
  


const toolbarSettings = reactive({
  commonInfo: {
    createDatetime: ref(""),
    processStatus: "",
    processSubStatus: "",
    isCollected:false,
    isFollowing:false,

  },
  selectedVaules: {
    humanNodeSelected: '',
    operation: "",
    urgency:"",
    rejectPath: "",
    rejectActivi: "",
    afterActivityId: "",
    transferToUserId: "",
    signatureType: "",
    signatureUsers: "",
    communicateUsers: "",
    circulateUsers: "",
  },
  transferToUserName: [],
  signaturePersons: [],
  communicatePersons: [],
  circulatePersons: [],

  //task的状态类型
  // isDraft: 草稿状态； isHistory: 历史或者草稿（对于当前登录用户）； isOnway:审批中； isAppended :追加任务
  //isCommunicated:沟通者； iscommunicatting 被沟通者；isSignatured:加签者；isSignaturing：被加签者；
  operationTemplate: [],
  rejectToActivities: [],
  modifyNodes: [
    /*
    {nodeName:'部门经理',nodeKey:'adferad',isRequired:false,nodeValues:'张三，里斯'},
    {nodeName:'总经理',nodeKey:'dfdasdf',isRequired:false,nodeValues:'王五，赵六'}
    */
  ],
  humanSelectNodes: [
    /*
  {flowElementName:'部门经理',flowElementId:'1'},  
  */
  ],
  inclusiveGateway:[],
  willgoNode: {
    currentNodeInfo: '',
    nextNodeInfo: ''
  },
  attachments: "",
  comments: ""
});


const props = defineProps({
  previewFormObj: {
      type: Object as any,
      default: {
        itemList: [],
        formConf: {},
      },
    },
    previewConfig: {
      type: Object as any,
      default: {},
    },
    saveFormData:{
      type: Function,  
      required: true
    }
});
const emit = defineEmits(['cancel','reload']);

const startTime = ref("");
const operation = ref<string>('');
const urgency = ref<string>("2");
const humanSelect = ref("");
const historyOperation = ref("");
const rejectPath = ref('');
const rejectActivi = ref('');
const afterActivityId = ref('');
const rejectActivis = ref<SelectProps[]>([]);
const transferToUserId = ref('');
const signatureType = ref('aftermeSignature');
const signatureUsers = ref('');
const communicateUsers = ref('');
const circulateUsers = ref('');
const appendTaskType = ref('');
const followingText = ref("跟踪流程");
const isFollowing = ref(false);
const isCollected = ref(false);
const modifyNodes = ref([]);
const currentSelectedActivitiyId = ref('');


// 当前主键
const bussid = ref('');

const getModifyactivityApproveUsers = () => {
  let allnodes = [];
   modifyNodes.value.forEach(element => {
    let ap={
      activityId:element.activityId,
      users:JSON.stringify(element.users)
    };  
    allnodes.push(ap);   
    
  });
  return allnodes; 
}

const getHumanSelectNodes = () => {
  let allnodes = [];
  toolbarSettings.humanSelectNodes.forEach(element => {
  //还没有选择，初始化 unknown
    if (!(element.selectNodeId==="unknown")) {
         let node: humanSelectNode = {
          gateWayId: element.gateWayId,
          selectNodeId: element.selectNodeId,
         }      
        allnodes.push(node);    
    }
  });
  return allnodes;
}


const focus = () => {
  console.log('focus');
};

const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};

const userRquest = reactive({
  comments: '',
  processDefinitionId: '',
  taskId: '',
  businessKey: '',
  approveUserId: "",
  attachments:"",
  processInstanceId:"",  
});

const validateOperation =() =>{
  if(toolbarSettings.commonInfo.processStatus === 'isOnway'){
    if(operation.value ===''){
      message.warning("请选择审批操作！");      
      return false;
    }      
   



  }  
  return true;
}


const handleSaveFormData= async()=>{
  console.log(props.previewConfig,"previewConfig11111111111")
  const formData=props.saveFormData(); 
  const data={
    id:props.previewConfig.businessKey,
    mapJson:JSON.stringify(formData.config),
    dataJson:JSON.stringify(formData.keyValueList)
  }
  const res=await saveFormDataValue(data);
  if(res.error=="200"){
    return res.result;
  }
  else{
    return "";
  }
}

const appoveOperation = async() => {  
  const id=await handleSaveFormData();
  console.log(id,"id11111111111111")
  if(id===""){
    message.error("保存失败")
    return false;
  }
  if(validateOperation()===false)
    return;
  //如果是草稿模式，分两种情况，一种是taskid，如果不为空，那么需要执行approve提交，如果为空，那么直接是发起
  bussid.value=id;
  userRquest.businessKey=id;
  userRquest.taskId = props.previewConfig.taskid;
  userRquest.approveUserId = userStore.getUserAccount;   
  userRquest.attachments = JSON.stringify(fileList.value); 
  userRquest.processInstanceId = props.previewConfig.procinstid;
  //这种是处理如果驳回到草稿节点的情况
  if(toolbarSettings.commonInfo.processStatus==='isDraft'&&userRquest.taskId !='')
  {
    operation.value = 'approve';
  }  
  //isDraft 为true 草稿箱里面（打开草稿箱，点击下面的提交按钮）
  if (operation.value === 'approve') {
   
    
   
    //actionClick(operation.value, approveRequest);
  }  
  

//emit('reload');


};

const fileList = ref<UploadProps['fileList']>([]);
const activeKey1 = ref(['2']);
const customStyle =
  'border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden';


// 提示信息弹窗
const msgModalOpen = ref(false);
const errorMsg = reactive({
  //默认信息类型
  resType: 'suecess',
  //默认提示信息
  resTypeMsg: '',
});

const previewRef = ref(null);

const showPreview = ref(false);
const loading = ref(false);


// 工具栏状态
const {  
  initToolBar,
} = monitorToolbar(previewRef, emit, loading, props.previewConfig, bussid, errorMsg, msgModalOpen);

const handleDeleteCancel = async () => {     
  props.previewConfig.taskid='';
  props.previewConfig.procinstid='';
  confirmVisible.value = false; 
}


const updateModifyNodes = (modifyNodes) => {
  modifyNodes.forEach(element => {
    if (element.nodeValues === "")
      element.nodeValues = [];

  });
}

const loadToolBarSettings = async (currentTaskId, processInstanceId, processDefinitionId) => {
  if (processDefinitionId == undefined) {
    processDefinitionId = ""
  }
  const res = await getToolbarSettings({
    taskid: currentTaskId,
    processInstanceId: processInstanceId,
    processDefinitionId: processDefinitionId
  });
  //如果是暂存的操作动作
  if (res.result.isSavedOperation == "true") {
    let newToolbarSetting = JSON.parse(res.result.businessContext);
    toolbarSettings.commonInfo = newToolbarSetting.commonInfo;
    toolbarSettings.operationTemplate = newToolbarSetting.operationTemplate;
    toolbarSettings.rejectToActivities = newToolbarSetting.rejectToActivities;
    toolbarSettings.humanSelectNodes = newToolbarSetting.humanSelectNodes;
    toolbarSettings.inclusiveGateway = newToolbarSetting.inclusiveGateway;
    toolbarSettings.modifyNodes = newToolbarSetting.modifyNodes;
    updateModifyNodes(toolbarSettings.modifyNodes);
    toolbarSettings.transferToUserName = newToolbarSetting.transferToUserName;
    toolbarSettings.willgoNode = newToolbarSetting.willgoNode;
    toolbarSettings.comments = newToolbarSetting.comments;
    toolbarSettings.signaturePersons = newToolbarSetting.signaturePersons;
    toolbarSettings.communicatePersons = newToolbarSetting.communicatePersons;
    toolbarSettings.selectedVaules = newToolbarSetting.selectedVaules;
    //toolbarSettings.attachments = newToolbarSetting.attachments;
    fileList.value = JSON.parse(newToolbarSetting.attachments);
    userRquest.comments = toolbarSettings.comments;    
    humanSelect.value = toolbarSettings.selectedVaules.humanNodeSelected;
    operation.value = toolbarSettings.selectedVaules.operation;
    urgency.value = toolbarSettings.selectedVaules.urgency;
    rejectActivi.value = toolbarSettings.selectedVaules.rejectActivi;
    rejectPath.value = toolbarSettings.selectedVaules.rejectPath;
    afterActivityId.value = toolbarSettings.selectedVaules.afterActivityId;
    transferToUserId.value = toolbarSettings.selectedVaules.transferToUserId;
    signatureType.value = toolbarSettings.selectedVaules.signatureType;
    signatureUsers.value = toolbarSettings.selectedVaules.signatureUsers;
    communicateUsers.value = toolbarSettings.selectedVaules.communicateUsers;
    circulateUsers.value = toolbarSettings.selectedVaules.circulateUsers;
    appendTaskType.value = toolbarSettings.commonInfo.processSubStatus;    
    isFollowing.value = toolbarSettings.commonInfo.isFollowing;
    isCollected.value = toolbarSettings.commonInfo.isCollected;
  }
  else {
    toolbarSettings.commonInfo = res.result.commonInfo;
    toolbarSettings.operationTemplate = res.result.operationTemplate;
    toolbarSettings.rejectToActivities = res.result.rejectToActivities;
    toolbarSettings.humanSelectNodes = res.result.humanSelectNodes;
    toolbarSettings.inclusiveGateway = res.result.inclusiveGateway;
    toolbarSettings.modifyNodes = res.result.modifyNodes;
    updateModifyNodes(toolbarSettings.modifyNodes);
    toolbarSettings.willgoNode = res.result.willgoNode;
    toolbarSettings.comments = res.result.comments;
    userRquest.comments = toolbarSettings.comments;
    toolbarSettings.attachments = res.result.attachments;
    humanSelect.value = toolbarSettings.selectedVaules.humanNodeSelected;
    operation.value = toolbarSettings.selectedVaules.operation;    
    rejectActivi.value = toolbarSettings.selectedVaules.rejectActivi;
    rejectPath.value = toolbarSettings.selectedVaules.rejectPath;
    afterActivityId.value = toolbarSettings.selectedVaules.afterActivityId;
    transferToUserId.value = toolbarSettings.selectedVaules.transferToUserId;
    //signatureType.value = toolbarSettings.selectedVaules.signatureType;
    signatureUsers.value = toolbarSettings.selectedVaules.signatureUsers;
    communicateUsers.value = toolbarSettings.selectedVaules.communicateUsers;
    circulateUsers.value = toolbarSettings.selectedVaules.circulateUsers;
    appendTaskType.value = toolbarSettings.commonInfo.processSubStatus;    
    isFollowing.value = toolbarSettings.commonInfo.isFollowing;
    if(isFollowing.value)  {
      followingText.value = "取消跟踪";
    }
    isCollected.value = toolbarSettings.commonInfo.isCollected;
    props.previewConfig.isCollected = isCollected.value;
  }
  if (toolbarSettings.commonInfo.processStatus != "isDraft") {
    let time = toolbarSettings.commonInfo.createDatetime;
    let dateTime = new Date(time.replace(/-/g, "/"));  // replace方法将 - 转为 /

    let dateNow = new Date();  // 获取当前时间
    let timeDiff = dateNow.getTime() - dateTime.getTime();  // 时间差的毫秒数
    // timeDiff = 时间戳差值

    let days = Math.floor(timeDiff / (24 * 3600 * 1000)); // 计算出天数
    let leavel1 = timeDiff % (24 * 3600 * 1000); // 计算去除天数后剩余的毫秒数
    let hours = Math.floor(leavel1 / (3600 * 1000)); // 计算天数后剩余的小时数
    let leavel2 = timeDiff % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
    let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数

    startTime.value = `${days}天${hours}时${minutes}分`;

  }  
}

watch(
  () => props.previewConfig,
  () => {
    if (props.previewConfig.form_type == '0') {
      showPreview.value = true;
      loading.value = false;
    }
  }, 
  {
    immediate: true,
  },
);

defineExpose({
  handleSubmit: onSubMit  
});
onMounted(() => {
  initToolBar(props.previewConfig);
  loadToolBarSettings(props.previewConfig.taskid, props.previewConfig.procinstid, props.previewConfig.processDefinitionId);  
});
</script>


<style lang="less" scoped>
.flex-buttom-box {
  display: flex;
  flex-wrap: wrap-reverse;
  gap: 10px;
}
</style>

<style scoped>
.demo-page-header :deep(tr:last-child td) {
  padding-bottom: 0;
}
</style>